import React, { Component } from 'react';
import sortBy from 'lodash/sortBy';
import get from 'lodash/get';
import Head from 'next/head';
import moment from 'moment';
import atob from 'atob';
import btoa from 'btoa';
import backgroundFightRecord from './background-fight-record.jpg';

const RoomInfo = ({ room_code, round_title, played_at, ratio }) => (
  <div
    style={{
      marginBottom: 30 * ratio,
      height: 40 * ratio,
      display: 'flex',
      marginLeft: 40 * ratio,
      marginRight: 40 * ratio,
      fontSize: `${28 / 16 * ratio}em`,
      alignItems: 'center',
      flexDirection: 'row',
    }}
  >
    <div style={{ flex: 1 }}>
      <span>房间：{room_code}</span>
      <span>{round_title}</span>
    </div>
    <span>{played_at}</span>
  </div>
);

const UserScore = ({ name, avatar, score, ratio }) => (
  <div
    style={{
      height: 85 * ratio,
      marginBottom: 15 * ratio,
      marginRight: 80 * ratio,
      display: 'flex',
      flexDirection: 'row',
      alignItems: 'center',
    }}
  >
    <div style={{ flex: 1, marginLeft: 130 * ratio, display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
      <img style={{ width: 70 * ratio, height: 70 * ratio }} src={backgroundFightRecord} alt="头像" />
      <span style={{ marginLeft: 30 * ratio, fontSize: `${36 / 16 * ratio}em` }}>{name}</span>
    </div>
    <span style={{ fontSize: `${60 / 16 * ratio}em` }}>{score > 0 ? `+${score}` : score}</span>
  </div>
);

const ScoreList = ({ scores, ratio }) => {
  return (
    <div style={{ marginTop: 76 * ratio }}>
      {sortBy(scores, s => -s.score).map(({ name, avatar, score }, index) => (
        <UserScore key={index} name={name} avatar={avatar} score={score} ratio={ratio} />
      ))}
    </div>
  );
};

const Records = ({ room_info, scores, ratio }) => {
  const { room_code, round_title, played_at } = room_info;
  return (
    <div
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        display: 'flex',
      }}
    >
      <div
        style={{
          width: '100%',
          marginLeft: 400 * ratio,
          marginRight: 100 * ratio,
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'space-between',
        }}
      >
        <ScoreList scores={scores} ratio={ratio} />
        <RoomInfo room_code={room_code} round_title={round_title} played_at={played_at} ratio={ratio} />
      </div>
    </div>
  );
};

// 背景图片的狂高
const size = {
  width: 1334,
  height: 750,
  min_ratio: 0 / 1334,
  //min_ratio: 547 / 1334,
};

const defaultProps = {
  played_at: moment().format('YYYY-MM-DD HH:mm:SS'),
  round_title: '桂林跑牌（3局）',
  room_code: '100001',
  room_id: '牌局唯一 id',
  scores: [
    { name: '玩家 1号', avatar: '头像地址', score: 50 },
    { name: '玩家 2号', avatar: '头像地址', score: -30 },
    { name: '玩家 3号', avatar: '头像地址', score: 20 },
    { name: '玩家 4号', avatar: '头像地址', score: -60 },
  ],
};

class App extends Component {
  state = {
    ratio: 1,
  };

  static defaultProps = defaultProps;

  static async getInitialProps({ pathname, query, asPath }) {
    // http://192.168.2.208:3000/?record=JTdCJTIycGxheWVkX2F0JTIyJTNBJTIyMjAxOC0wOC0wMyUyMDE2JTNBMTUlM0E0MSUyMCUyMiUyQyUyMnJvdW5kX3RpdGxlJTIyJTNBJTIyJUU2JUExJTgyJUU2JTlFJTk3JUU4JUI3JTkxJUU3JTg5JThDJUVGJUJDJTg4MTclRTUlQjElODAlRUYlQkMlODklMjIlMkMlMjJyb29tX2NvZGUlMjIlM0ElMjI1MzM4MjMlMjIlMkMlMjJyb29tX2lkJTIyJTNBJTIyJUU3JTg5JThDJUU1JUIxJTgwJUU1JTk0JUFGJUU0JUI4JTgwJUU3JTlBJTg0aWQlMjIlMkMlMjJzY29yZXMlMjIlM0ElNUIlN0IlMjJuYW1lJTIyJTNBJTIyJUU3JThFJUE5JUU1JUFFJUI2MSVFNSU4RiVCNyUyMiUyQyUyMmF2YXRhciUyMiUzQSUyMiVFNSVBNCVCNCVFNSU4MyU4RiVFNSU5QyVCMCVFNSU5RCU4MCUyMiUyQyUyMnNjb3JlJTIyJTNBNTAlN0QlMkMlN0IlMjJuYW1lJTIyJTNBJTIyJUU3JThFJUE5JUU1JUFFJUI2MiVFNSU4RiVCNyUyMiUyQyUyMmF2YXRhciUyMiUzQSUyMiVFNSVBNCVCNCVFNSU4MyU4RiVFNSU5QyVCMCVFNSU5RCU4MCUyMiUyQyUyMnNjb3JlJTIyJTNBLTUwJTdEJTJDJTdCJTIybmFtZSUyMiUzQSUyMiVFNyU4RSVBOSVFNSVBRSVCNjMlRTUlOEYlQjclMjIlMkMlMjJhdmF0YXIlMjIlM0ElMjIlRTUlQTQlQjQlRTUlODMlOEYlRTUlOUMlQjAlRTUlOUQlODAlMjIlMkMlMjJzY29yZSUyMiUzQTUwJTdEJTJDJTdCJTIybmFtZSUyMiUzQSUyMiVFNyU4RSVBOSVFNSVBRSVCNjQlRTUlOEYlQjclMjIlMkMlMjJhdmF0YXIlMjIlM0ElMjIlRTUlQTQlQjQlRTUlODMlOEYlRTUlOUMlQjAlRTUlOUQlODAlMjIlMkMlMjJzY29yZSUyMiUzQS01MCU3RCU1RCU3RA==
    try {
      console.log({ query, asPath, pathname });
      const record = get(query, 'record', btoa(encodeURIComponent(JSON.stringify(defaultProps))));
      const uri = decodeURIComponent(atob(record));
      const props = JSON.parse(uri);
      return { query, asPath, ...props };
    } catch (error) {
      console.error('error', error);
      return defaultProps;
    }
  }

  componentDidMount() {
    this.setRatio();
  }

  setRatio() {
    const width = document.documentElement.clientWidth;
    const r = width / size.width;
    this.setState({ ratio: r < size.min_ratio ? size.min_ratio : r });
  }

  render() {
    const { room_code, played_at, round_title, scores } = this.props;
    console.log({ props: this.props, room_code: room_code });
    console.log({ props: this.props, room_code: room_code });
    const room_info = {
      room_code,
      round_title,
      played_at,
    };
    const { ratio } = this.state;
    const [width, height] = [size.width * ratio, size.height * ratio];
    return (
      <div style={{ position: 'relative', width, height }}>
        <span>{JSON.stringify(this.props)}</span>
        <style global jsx>{`
          body {
            font: normal 100% Helvetica, Arial, sans-serif;
            background-color: white;
            pointer-events: none;
          }
        `}</style>
        <Head>
          <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, shrink-to-fit=no" />
        </Head>
        <img style={{ opacity: 0.2, width, height }} src={backgroundFightRecord} alt="战绩图片" />
        <Records room_info={room_info} scores={scores} ratio={ratio} />
      </div>
    );
  }
}

const styles = {};

export default App;
